package ksj.common.tasks;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import ksj.common.utils.Utility;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;

import bean.Schedules;
import bsh.EvalError;
import bsh.Interpreter;
import ksj.common.utils.net.GenericServiceConsumer;

public class RabbitMQTask implements Job {
	private final Logger log = LoggerFactory.getLogger(this.getClass());
	public static final String SCHEDULE = "schedule";

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		JobDataMap dataMap = context.getJobDetail().getJobDataMap();
		Gson gson = new Gson();

		Schedules task = (Schedules) dataMap.get(SCHEDULE);
		String configJSON = task.getConfig_json();
		Long id = task.getId();
		String message = task.getMessage();
		String taskName = task.getTask_name();
		String variablesString = task.getVariables();

		JSONObject config = new JSONObject(configJSON);
		String host = config.getString("host");
		String port = config.getString("port");
		String user = config.getString("user");
		String password = config.getString("password");
		String exchangeName = config.getString("exchangeName");
		String exchangeType = config.getString("exchangeType");
		String queueName = config.getString("queueName");
		String routingKey = config.getString("routingKey");

		JSONObject variablesJSON = new JSONObject(variablesString);

		JSONArray variablesArray = variablesJSON.getJSONArray("variables");

		for (Object object : variablesArray) {
			JSONObject variableElements = new JSONObject(object.toString());
			boolean compile = Boolean.valueOf(variableElements.getString("compile"));
			Iterator<?> keys = variableElements.keys();

			while (keys.hasNext()) {
				String key = (String) keys.next();
				if (!key.equals("compile")) {
					if (compile) {
						String valueToCalculate = variableElements.getString(key);
						Interpreter i = new Interpreter();
						try {
							String calculated = (String) i.eval(valueToCalculate);

							message = message.replace("${"+key+"}", calculated);
						} catch (EvalError e) {
							e.printStackTrace();
						}

					} else {
						String value = variableElements.getString(key);
						message = message.replace("${"+key+"}", value);
					}
				}
			}
		}

		List<BasicNameValuePair> basicNameValuePairs = new ArrayList<BasicNameValuePair>();
		basicNameValuePairs.add(new BasicNameValuePair("host", host));
		basicNameValuePairs.add(new BasicNameValuePair("queueName", queueName));
		basicNameValuePairs.add(new BasicNameValuePair("message", message));
		basicNameValuePairs.add(new BasicNameValuePair("userName", user));
		basicNameValuePairs.add(new BasicNameValuePair("password", password));
		basicNameValuePairs.add(new BasicNameValuePair("portNumber", port));
		basicNameValuePairs.add(new BasicNameValuePair("routingKey", routingKey));

		JSONObject object = GenericServiceConsumer.consumeServicePOST("/rabbitmq/executor/publishMessage", "localhost", 8833, "",
				basicNameValuePairs);
		log.info(object.getString("status"));
	}

}
